<template>
  <!-- 数据分析 -->
  <div class="dashboard-container">
    <SearchTable :show-pagination="false">
      <template slot="header">
        <el-row style="width: 100%">
          <!-- <el-input
            style="width: 300px"
            @input="searchKeyWord"
            clearable
            placeholder="请输入用户名搜索关键词"
            v-model="keyWord"
          ></el-input>-->
          <el-date-picker
            v-model="range"
            type="daterange"
            align="right"
            @change="rangeChange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-row>
        <!-- <el-button type="primary" @click="addStore">数据分析</el-button> -->
      </template>
      <template>
        <div class="coun-analyse-container">
          <div id="cate-box" ref="cateBox"></div>
          <div id="date-box" ref="dateBox"></div>
        </div>
      </template>
    </SearchTable>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SearchTable from "@/components/TableTemplate/SearchTable";
import { getTotalCategoryMoney, getTotalMoneyByOrderDate } from "@/api/user";
import AddDialog from "./components/AddDialog";
import * as echarts from "echarts";
export default {
  components: {
    SearchTable,
    AddDialog,
  },
  data() {
    return {
      cateInfoList: [], //按分类
      dateInfoList: [], //按日期
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      range: "",
    };
  },
  async mounted() {
    this.initEcharts();
  },
  computed: {
    ...mapGetters(["name", "token"]),
  },
  methods: {
    rangeChange(val) {
      console.log(val);
      this.initEcharts();
    },
    async initEcharts() {
      await this.getTotalCategoryMoney();
      await this.getTotalMoneyByOrderDate();
      this.initCateChart();
      this.initDateChart();
    },
    initCateChart() {
      let yList = this.cateInfoList.map((item) => item.total_money || 0);
      let xData = this.cateInfoList.map((item) => item.category_name || "分类");
      console.log(yList, xData);
      let color = [
        "#CC1CAA",
        "#8D67FF",
        "#00FFFF",
        "#48DE13",
        "#FFC516",
        "#DC3E14",
        "#8E16F8",
      ];

      let dom = 800;
      let barWidth = dom / 20;
      let colors = [];
      for (let i = 0; i < 4; i++) {
        colors.push({
          type: "linear",
          x: 0,
          x2: 1,
          y: 0,
          y2: 0,
          colorStops: [
            {
              offset: 0,
              color: "#73fcff", // 最左边
            },
            {
              offset: 0.5,
              color: "#86eef1", // 左边的右边 颜色
            },
            {
              offset: 0.5,
              color: "#5ad6d9", // 右边的左边 颜色
            },
            {
              offset: 1,
              color: "#3dc8ca",
            },
          ],
        });
      }
      const option = {
        title: {
          text: "品类销售总额",
          x: "46%",
          y: "4%",
          textStyle: {
            color: "#fff",
            fontSize: "22",
          },
          subtextStyle: {
            color: "#90979c",
            fontSize: "16",
          },
        },
        backgroundColor: "#010d3a",
        //提示框
        tooltip: {
          trigger: "axis",
          formatter: "{b} : {c} 元",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        /**区域位置*/
        grid: {
          left: "10%",
          right: "10%",
          top: "15%",
          bottom: "10%",
        },
        //X轴
        xAxis: {
          data: xData,
          type: "category",
          name: "商品分类",
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(255,255,255,1)",
              shadowColor: "rgba(255,255,255,1)",
              shadowOffsetX: "20",
            },
            symbol: ["none", "arrow"],
            symbolOffset: [0, 25],
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            margin: 30,
            fontSize: 15,
          },
        },
        yAxis: {
          name: "销售额：元",
          nameLocation: "end", // 设置名称位置为中间
          nameTextStyle: {
            color: "#FFffff", // 设置名称颜色为红色
            fontSize: 15,
          },
          show: true,
          splitNumber: 4,
          axisLine: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "#075858",
            },
          },
          axisLabel: {
            color: "#FFFFFF",
            margin: 30,
            fontSize: 15,
          },
        },
        series: [
          {
            type: "bar",
            barWidth: barWidth,
            itemStyle: {
              normal: {
                color: function (params) {
                  return colors[params.dataIndex % 7];
                },
              },
            },
            label: {
              show: false,
              position: [barWidth / 2, -(barWidth + 20)],
              color: "#ffffff",
              fontSize: 14,
              fontStyle: "bold",
              align: "center",
            },
            data: yList,
          },
          {
            z: 2,
            type: "pictorialBar",
            data: yList,
            symbol: "diamond",
            symbolOffset: [0, "50%"],
            symbolSize: [barWidth, barWidth * 0.5],
            itemStyle: {
              normal: {
                color: function (params) {
                  return colors[params.dataIndex % 7];
                },
              },
            },
          },
          {
            z: 3,
            type: "pictorialBar",
            symbolPosition: "end",
            data: yList,
            symbol: "diamond",
            symbolOffset: [0, "-50%"],
            symbolSize: [barWidth, barWidth * 0.5],
            itemStyle: {
              normal: {
                borderWidth: 0,
                color: function (params) {
                  return colors[params.dataIndex % 7].colorStops[0].color;
                },
              },
            },
          },
        ],
      };

      echarts.init(this.$refs.cateBox).setOption(option);
    },
    initDateChart() {
      var xData = this.dateInfoList.map((item) => item.order_date);
      const yData = this.dateInfoList.map((item) => item.total_money);
      const option = {
        // backgroundColor: "#344b58",
        backgroundColor: "#010d3a",
        title: {
          text: "每日销售额",
          x: "4%",
          textStyle: {
            color: "#fff",
            fontSize: "22",
          },
          subtextStyle: {
            color: "#90979c",
            fontSize: "16",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            textStyle: {
              color: "#fff",
            },
          },
          formatter: function (params) {
            // params 是一个数组，包含所有系列的数据
            let tooltipHtml = "";
            params.forEach((param) => {
              tooltipHtml += `<div style="margin-bottom: 5px;">`;
              tooltipHtml += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
              tooltipHtml += `<span style="color:#000;">${param.seriesName}:</span>`;
              tooltipHtml += `<span style="color:#000;">${param.value} 元</span>`;
              tooltipHtml += `</div>`;
            });
            return tooltipHtml;
          },
        },
        grid: {
          borderWidth: 0,
          top: 110,
          bottom: 95,
          textStyle: {
            color: "#fff",
          },
        },

        calculable: true,
        xAxis: [
          {
            name: "日期",
            nameTextStyle: {
              color: "#FFffff", // 设置名称颜色为红色
              fontSize: 15,
            },
            type: "category",

            axisLine: {
              lineStyle: {
                color: "#90979c",
              },
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            splitArea: {
              show: false,
            },
            axisLabel: {
              interval: 0,
            },
            data: xData,
          },
        ],
        yAxis: [
          {
            type: "value",
            //y轴名称
            name: "单位：元",
            nameLocation: "end", // 设置名称位置为中间
            nameTextStyle: {
              color: "#FFffff", // 设置名称颜色为红色
              fontSize: 15,
            },
            //y轴线
            splitLine: {
              show: false,
            },
            axisLine: {
              lineStyle: {
                color: "#90979c",
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              interval: 0,
            },
            splitArea: {
              show: false,
            },
          },
        ],
        dataZoom: [
          {
            show: true,
            height: 30,
            xAxisIndex: [0],
            bottom: 30,
            start: 0,
            end: 100,
            handleIcon:
              "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
            handleSize: "110%",
            handleStyle: {
              color: "#d3dee5",
            },
            textStyle: {
              color: "#fff",
            },
            borderColor: "#90979c",
          },
          {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 35,
          },
        ],
        series: [
          {
            name: "日销售额",
            type: "line",
            stack: "总量",
            barMaxWidth: 35,
            barGap: "10%",
            itemStyle: {
              normal: {
                color: "rgba(255,144,128,1)",
                label: {
                  show: true,
                  textStyle: {
                    color: "#fff",
                  },
                  position: "insideTop",
                  formatter: function (p) {
                    return p.value > 0 ? p.value : "";
                  },
                },
              },
            },
            data: yData,
          },
        ],
      };
      echarts.init(this.$refs.dateBox).setOption(option);
    },
    showImgDialog(storeImg) {
      this.imgDialogVisible = true;
      this.imgDialogData = storeImg;
    },
    async getTotalCategoryMoney() {
      // 提取 Date 对象并格式化日期

      if (this.range) {
        const startDate = new Date(this.range[0]);
        const endDate = new Date(this.range[1]);
        const start_time = startDate.toLocaleDateString("en-CA"); // 使用 'en-CA' 格式化为 YYYY-MM-DD
        const end_time = endDate.toLocaleDateString("en-CA"); // 使用 'en-CA' 格式化为 YYYY-MM-DD

        const { data: res } = await getTotalCategoryMoney({
          start_time,
          end_time,
        });
        this.cateInfoList = res || [];
      } else {
        const { data: res } = await getTotalCategoryMoney();
        this.cateInfoList = res || [];
      }
    },
    async getTotalMoneyByOrderDate() {
      if (this.range) {
        const startDate = new Date(this.range[0]);
        const endDate = new Date(this.range[1]);
        const start_time = startDate.toLocaleDateString("en-CA"); // 使用 'en-CA' 格式化为 YYYY-MM-DD
        const end_time = endDate.toLocaleDateString("en-CA"); // 使用 'en-CA' 格式化为 YYYY-MM-DD

        const { data: res } = await getTotalMoneyByOrderDate({
          start_time,
          end_time,
        });
        this.dateInfoList = res || [];
      } else {
        const { data: res } = await getTotalMoneyByOrderDate();
        this.dateInfoList = res || [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  width: 100%;
  height: 100%;
}
.link-list {
  .el-link {
    margin: 0 2px;
  }
}
.img-box {
  margin-left: 65px;
  width: 80px;
  height: 120px;
  display: block;
}

.coun-analyse-container {
  display: flex;
  align-items: center;
  height: 100%;
  gap: 20px;
  #cate-box {
    flex: 1;
    height: 100%;
    background-color: #eee;
  }
  #date-box {
    flex: 1;
    height: 100%;
    background-color: #eee;
  }
  .el-card {
    padding: 20px;
    .flex-center {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
      margin-top: 50px;
    }
  }
}
</style>
